package com.tx;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DBUtil {
    static{ //静态块 - 第一次加载此类时被优先执行
        //2、注册驱动
        try{
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        }catch (Exception e){
            //e.printStackTrace();
            System.out.println("数据库驱动加载失败");
        }
    }
    /* 工具类中的变量一般为私有 */
    private final static String url = "jdbc:mysql://121.196.166.117:3306/estoredbs?useSSL=false";
    private final static String user = "root";
    private final static String password = "jisuanji2022";
    /** 获取数据库连接 */
    public static Connection getConnection(){
        //3、获取数据库连接
        Connection conn = null;
        try{
            conn = DriverManager.getConnection(url, user, password);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("数据库连接异常");
        }
        return conn;
    }

    /** 关闭资源 */
    public static void closeResource(Connection conn, Statement stmt, ResultSet rs){
        /** 关闭结果集 */
        try{
            if(rs != null){
                if(!rs.isClosed()){
                    rs.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //关闭SQL操作对象
        try{
            if(stmt != null){
                if(!stmt.isClosed()){
                    stmt.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //关闭连接
        try{
            if(conn != null){
                if(!conn.isClosed()){
                    conn.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
